package com.xbjtech.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserController {
	
	@GetMapping("/login")
	public String login() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			return "redirect:/mainIndex";
		}
		return "login";
	}
	
	@PostMapping("/login")
	public String login(String username, 
			String password, 
			@RequestParam(defaultValue = "false") Boolean remenberMe, Model model) {
		// 校验
		if ("".equals(username)) {
			model.addAttribute("errorMessage", "请输入用户名");
			return "login";
		}
		if ("".equals(password)) {
			model.addAttribute("errorMessage", "请输入密码");
			return "login";
		}
		// 登陆
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            token.setRememberMe(remenberMe);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
            	model.addAttribute("errorMessage", "用户名不存在");
    			return "login";
            } catch (IncorrectCredentialsException ice) {
            	model.addAttribute("errorMessage", "用户名和密码不匹配");
    			return "login";
            } catch (AuthenticationException ae) {
            	model.addAttribute("errorMessage", "登陆失败");
    			return "login";
            }
        }
		return "redirect:/mainIndex";
	}
	
}
